#include "server/Server.hpp"
#include "exception/Exception.hpp"
#include "system/socket/SocketExceptions.hpp"
#include <iostream>
namespace ServerServer
{
	Server::Server(
			unsigned int iPortNumber,
			int iMaxQueueSize,
			SystemSocket::AbstractConnectionProcessor * iProcessor):
			_socket(iPortNumber, iMaxQueueSize),_processor(iProcessor)
	{

	}

	Server::~Server()
	{
		_socket.closeSocket();
	}

	void Server::runThreadImpl()
	{
		try
		{
			// open socket
			_socket.openSocket();
			_socket.listen();
			_socket.setNonBlocking();

			while(1)
			{
				SystemSocket::Connection * aConnection = _socket.accept();

				if(aConnection)
				{
					// process connection
					_processor->process(aConnection);
				}
				else
				{
					if(!this->isAlive())
					{
						Thread::exit();
					}
				}
			}
		}
		catch(Exception::BaseException & aExcept)
		{
			std::cerr << "The server was stopped. Exception caught: " << aExcept.what() << std::endl;
		}

	}


};
